package dbops

import (
	"database/sql"
	"encoding/json"
	"os"
)

type dbConfig struct {
	DriverName string `json:"driverName"`
	DriverURL  string `json:"driverURL"`
}

var (
	ConnDb *sql.DB
	err    error
)

func init() {
	config := getDBConfig()
	driverName := config.DriverName
	driverURL := config.DriverURL
	ConnDb, err = sql.Open(driverName, driverURL) // 不需要 :=
	if err != nil {
		panic(err.Error())
	}
}

func getDBConfig() *dbConfig {
	filePath := "./configs/dbconfig.json"
	file, e := os.Open(filePath)
	defer file.Close()
	if e != nil {
		panic(e)
	}

	config := &dbConfig{}
	decoder := json.NewDecoder(file)
	e = decoder.Decode(config)
	if e != nil {
		panic(e.Error())
	}
	return config
}
